<script setup>
import { ref, watch } from 'vue'
import { useCounterStore } from '@/stores/counter'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
const loading = ref(false)
const counter = useCounterStore()
const route = useRoute()
const form = ref({
    type: 1,
    radio: 1,
    title: '',
    list: [],
    answerRemark: '',
    path: ''
})

// 创建表单引用用于验证
const formRef = ref()

const emit = defineEmits(['onTitleFocus', 'onAnswerFocus'])

// 表单验证规则
const rules = {
    title: [
        { required: true, message: '请输入题目', trigger: 'blur' }
    ],
    list: [
        {
            validator: (rule, value, callback) => {
                if (form.value.type == 1) {
                    if (!value || value.length === 0) {
                        callback(new Error('请至少添加一个选项'))
                    } else {
                        const emptyOption = value.find(item => !item.text || item.text.trim() === '')
                        if (emptyOption) {
                            callback(new Error('选项内容不能为空'))
                        } else {
                            callback()
                        }
                    }
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    answerRemark: [
        {
            validator: (rule, value, callback) => {
                if (form.value.type != 1 && (!value || value.trim() === '')) {
                    callback(new Error('请输入答案'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

function addAnswer() {
    if (form.value.list.length > 3 && form.value.type == 1) {
        ElMessage({
            type: 'warning',
            message: '目前最多添加4个选项',
        })
        return
    }
    form.value.list.push({
        key: Date.now(),
        text: ''
    })
}

function deleteAnswer(key) {
    ElMessageBox.confirm(
        '确认删除该选项?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            const index = form.value.list.findIndex(item => item.key === key)
            if (index > -1) {
                form.value.list.splice(index, 1)
            }
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
        })
        .catch(() => { })
}

async function sumit() {
    // 触发表单验证
    try {
        await formRef.value.validate()
        counter.saveMenu(form.value.path, form.value.answerRemark, form.value.title)
        ElMessage({
            type: 'success',
            message: '保存成功',
        })
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '请填写完整表单',
        })
    }
}

function titleFocus(type, form) {
    // counter.updateTitle(form.value.title, form)
    emit('onTitleFocus', type, form)
}

function titleBlur(value, form) {
    counter.updateTitle(value, form)
}

function answerFocus(type, form, item) {
    emit('onAnswerFocus', type, form, item)
}

function answerBlur(value, form, item) {
    counter.updateList(value, form, item.key)
}

// 深拷贝函数
function deepClone(obj) {
    try {
        return JSON.parse(JSON.stringify(obj));
    } catch (e) {
        return obj;
    }
}

function checkChange(item) {
    if (form.value.radio == '1') {
        // 单选题：确保只有一个正确答案
        form.value.list.forEach(option => {
            if (option.key !== item.key) {
                option.isCorrect = false;
            }
        });
    }
    counter.updateCorrect(item.isCorrect, form, item.key)
}

watch(() => counter.menu, (val) => {
    if (val) {
        const found = val.find(item => item.path == route.path)
        if (found) {
            // 使用深拷贝避免影响原始数据
            const clonedForm = deepClone(found)
            Object.assign(form.value, clonedForm)
        }
    }
}, {
    immediate: true,
    deep: true
})

watch(() => route.path, (val) => {
    if (val) {
        loading.value = true
        const found = counter.menu.find(item => item.path == val)
        if (found) {
            // 使用深拷贝避免影响原始数据
            const clonedForm = deepClone(found)
            Object.assign(form.value, clonedForm)
        }
        setTimeout(() => {
            loading.value = false
        }, 300)
    }
}, {
    immediate: true,
    deep: true
})
</script>

<template>
    <section class="content">
        <div v-loading="loading">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
                <h4 class="title">题目
                    <el-tag type="primary" v-if="form.type == 1">{{ form.radio == 1 ? '单选' : '多选' }}</el-tag>
                    &nbsp;
                    <el-tag type="success">{{ form.type == 1 ? '情绪问答题' : '问答陈述题' }}</el-tag>
                </h4>
                <el-row>
                    <el-col :span="22">
                        <el-form-item prop="title">
                            <el-input v-model="form.title" type="textarea" clearable placeholder="请输入题目"
                                @focus="titleFocus(1, form)" @blur="titleBlur(form.title, form)" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-button type="primary" @click="addAnswer"
                        v-if="form.list.length < 4 && form.type == 1">添加答案</el-button>
                </el-row>
                <el-row v-if="form.type == 1">
                    <el-col :span="24">
                        <el-form-item prop="list">
                            <ul style="width: 100%;">
                                <li class="answer" v-for="item in form.list" :key="item.key" style="width: 100%;">
                                    <el-form-item>
                                        <el-input v-model="item.text" clearable style="width: 90%;" placeholder="请输入答案"
                                            @focus="answerFocus(2, form, item)"
                                            @blur="answerBlur(item.text, form, item)" />
                                        <!-- <el-checkbox v-model="item.isCorrect" style="margin-left:10px ;"
                                            @change="checkChange(item)" /> -->
                                        <el-icon style="margin-left: 10px; cursor: pointer;">
                                            <Delete @click="deleteAnswer(item.key)" />
                                        </el-icon>
                                    </el-form-item>
                                </li>
                            </ul>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-else style="margin-top: 20px;">
                    <el-col :span="22">
                        <el-form-item prop="answerRemark">
                            <el-input v-model="form.answerRemark" type="textarea" clearable placeholder="请输入答案" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="submit">
                <el-button type="primary" @click="sumit">保存</el-button>
            </div>
        </div>
    </section>
</template>

<style scoped lang="scss">
.content {
    width: 100%;
    padding: 10px 20px;
}

.title {
    margin: 10px 0;
}

.answer {
    margin: 20px 0;
}

.submit {
    display: flex;
    justify-content: flex-end;
}
</style>